package cn.com.agree.dopomapping.valueobjectmapping.serializemapping.infrastructure.converter;

import cn.com.agree.dopomapping.valueobjectmapping.serializemapping.domain.StudentDO;
import cn.com.agree.dopomapping.valueobjectmapping.serializemapping.domain.valueobject.CourseValueObj;
import cn.com.agree.dopomapping.valueobjectmapping.serializemapping.infrastructure.po.StudentPO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;
import org.mapstruct.Named;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
public interface StudentConverter {

    @Mapping(target = "courses", qualifiedByName = "serializeAddress")
    StudentPO toPO(StudentDO studentDO);

    @Mapping(target = "courses", qualifiedByName = "deserializeAddress")
    StudentDO toEntity(StudentPO studentPO);


    @Named("serializeAddress")
    default String serializeAddress(List<CourseValueObj> courses) {
        if (Objects.nonNull(courses)) {
            try {
               return new ObjectMapper().writeValueAsString(courses);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    @Named("deserializeAddress")
    default List<CourseValueObj> deserializeAddress(String courses) {
        if (courses != null && !"".equals(courses.trim())) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, CourseValueObj.class);
                return objectMapper.readValue(courses, collectionType);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
